﻿using EnvControlLib;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.Prism.ViewModel;
using Microsoft.Practices.ServiceLocation;
using InteractiveWhiteboardManagement.Base.Common;
using InteractiveWhiteboardManagement.Base.Events;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using InteractiveWhiteboardManagement.Base.ViewModels;
using Microsoft.Practices.Prism.Commands;
using System.ComponentModel.DataAnnotations;
using System.Security.AccessControl;
using Microsoft.Practices.Unity;
using FileLib;
using EnvCommonUtility;
using CommonBase;
using CommonClass;

namespace InteractiveWhiteboardManagement.ViewModels
{
    public class ViewModel_Shell : WorkspaceViewModel
    {
        #region Private Fields

        private Accordion _navigationPanel; // 导航面板
        private TabControl _splitPanel; // 用户区
        private DelegateCommand _cmdConfiguration, _cmdRegistration, _cmdAboutUs;

        private readonly IServiceLocator _serviceLocator;
        private readonly IModuleManager _moduleManager;
        private readonly IModuleCatalog _moduleCatalog;
        private readonly IRegionManager _regionManager;
        private readonly IEventAggregator _eventAggregator;
        private readonly IUnityContainer _container;

        #endregion

        #region Constructor

        public ViewModel_Shell(IServiceLocator serviceLocator,
            IModuleManager moduleManager, IModuleCatalog moduleCatalog,
            IRegionManager regionManager, IEventAggregator eventAggregator,
            IUnityContainer container)
        {
            this._serviceLocator = serviceLocator;
            this._moduleManager = moduleManager;
            this._moduleCatalog = moduleCatalog;
            this._regionManager = regionManager;
            this._eventAggregator = eventAggregator;
            this._container = container;

            #region 系统初始化操作
            try
            {
                Utilities.DatabaseName = "db_IWM";
                Utilities.ChangeDBFileAccessControl(Utilities.DatabaseName); // 增加 mdb 文件修改权限
                _initializeINIFile(); // 初始化 ini 文件
                Utilities.BackupDatabase("BackupDirectory", Utilities.DatabaseName); // 自动备份数据库
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }

            #region 模块加载
            _changeIndicatorState(true);
            // 模块加载完全时，才能做下一步操作！
            moduleManager.LoadModuleCompleted += (s, e) =>
            {
                _changeIndicatorState(false);
            };
            #endregion

            #region 模块间通信
            // 所有子模块操作后的主模块入口，回到主模块执行操作
            OpenModelEvent openEvent = _eventAggregator.GetEvent<OpenModelEvent>();
            openEvent.Subscribe(_manageData, ThreadOption.UIThread, true,
                x => x.ModelName == this.GetType().Name);
            #endregion
            #endregion

            #region 注册界面
            this._container.RegisterType<object, Views.View_Configuration>(ViewNames.InteractiveWhiteboardManagement_Configuration,
                new ContainerControlledLifetimeManager()); // 单例模式，注册配置管理界面
            this._container.RegisterType<object, Views.View_Registration>(ViewNames.InteractiveWhiteboardManagement_Registration,
                new ContainerControlledLifetimeManager()); // 单例模式，注册产品注册界面
            this._container.RegisterType<object, Views.View_AboutUs>(ViewNames.InteractiveWhiteboardManagement_AboutUs,
                new ContainerControlledLifetimeManager()); // 单例模式，注册关于我们界面
            #endregion
        }

        #endregion

        #region Property

        /// <summary>
        /// 是否显示 进度条
        /// </summary>
        public bool Indicator_IsBusy { get; private set; }

        /// <summary>
        /// 配置管理
        /// </summary>
        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_Configuration
        {
            get
            {
                if (_cmdConfiguration == null)
                {
                    _cmdConfiguration = new DelegateCommand(_configuration, _canConfiguration);
                }
                return _cmdConfiguration;
            }
        }

        /// <summary>
        /// 产品注册
        /// </summary>
        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_Registration
        {
            get
            {
                if (_cmdRegistration == null)
                {
                    _cmdRegistration = new DelegateCommand(_registration, _canRegistration);
                }
                return _cmdRegistration;
            }
        }

        /// <summary>
        /// 关于我们
        /// </summary>
        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_AboutUs
        {
            get
            {
                if (_cmdAboutUs == null)
                {
                    _cmdAboutUs = new DelegateCommand(_aboutUs, _canAboutUs);
                }
                return _cmdAboutUs;
            }
        }

        #endregion

        #region Private Methods

        #region DelegateCommand

        private bool _canConfiguration()
        {
            return true;
        }

        private bool _canRegistration()
        {
            return true;
        }

        private bool _canAboutUs()
        {
            return true;
        }


        /// <summary>
        /// 配置管理
        /// </summary>
        private void _configuration()
        {
            this._regionManager.RequestNavigate(RegionNames.ContentRegion,
                ViewNames.InteractiveWhiteboardManagement_Configuration); // 显示配置管理界面
        }

        /// <summary>
        /// 产品注册
        /// </summary>
        private void _registration()
        {
            this._regionManager.RequestNavigate(RegionNames.ContentRegion,
                ViewNames.InteractiveWhiteboardManagement_Registration); // 显示产品注册界面
        }

        /// <summary>
        /// 关于我们
        /// </summary>
        private void _aboutUs()
        {
            this._regionManager.RequestNavigate(RegionNames.ContentRegion,
                ViewNames.InteractiveWhiteboardManagement_AboutUs); // 显示关于我们界面
        }

        #endregion

        /// <summary>
        /// 修改 进度条 状态
        /// </summary>
        /// <param name="state"></param>
        private void _changeIndicatorState(bool state)
        {
            Indicator_IsBusy = state;
            base.OnPropertyChanged("Indicator_IsBusy");
        }

        

        /// <summary>
        /// 初始化 ini 文件
        /// </summary>
        private void _initializeINIFile()
        {
            // ini 文件 初始化
            bool isOK = true; // 表示 ini 文件中的值是正常的
            INIOperation iniOperation = new INIOperation();
            string iniPath = string.Format(@"{0}\{1}\{2}.ini", Environment.CurrentDirectory,
                "DataBase", Utilities.DatabaseName);

            // ini 文件 获取值
            int outValueLength; // ini 键值字符串长度
            string iniTabCountMonitorScreen = iniOperation.ReadValue(EnvUtilities.INI_SECTIONNAME_MONITORSCREEN,
                EnvUtilities.INI_KEYNAME_MONITORSCREEN_TABCOUNT,
                iniPath, out outValueLength); // 读 ini 文件中的监控画面打开的最大个数
            string iniTimerMonitorScreen = iniOperation.ReadValue(EnvUtilities.INI_SECTIONNAME_MONITORSCREEN,
                EnvUtilities.INI_KEYNAME_MONITORSCREEN_INTERVAL,
                iniPath, out outValueLength); // 读 ini 文件中的监控画面更新秒数
            string iniTimerHeartbeat = iniOperation.ReadValue(EnvUtilities.INI_SECTIONNAME_HEARTBEAT,
                EnvUtilities.INI_KEYNAME_HEARTBEAT_INTERVAL,
                iniPath, out outValueLength); // 读 ini 文件中的心跳间隔秒数

            // 判断值域
            ushort outTabCountMonitorScreen, outTimerMonitorScreen, outTimerHeartbeat;
            if(string.IsNullOrWhiteSpace(iniTabCountMonitorScreen) ||
                !ushort.TryParse(iniTabCountMonitorScreen, out outTabCountMonitorScreen) ||
                outTabCountMonitorScreen < EnvUtilities.TABCOUNT_MONITORSCREEN_MIN ||
                outTabCountMonitorScreen > EnvUtilities.TABCOUNT_MONITORSCREEN_MAX)
            {
                isOK = false;
                outTabCountMonitorScreen = EnvUtilities.TABCOUNT_MONITORSCREEN_DEFAULT;
            }

            if (string.IsNullOrWhiteSpace(iniTimerMonitorScreen) ||
                !ushort.TryParse(iniTimerMonitorScreen, out outTimerMonitorScreen) ||
                outTimerMonitorScreen < EnvUtilities.TIMER_MONITORSCREEN_MIN ||
                outTimerMonitorScreen > EnvUtilities.TIMER_MONITORSCREEN_MAX)
            {
                isOK = false;
                outTimerMonitorScreen = EnvUtilities.TIMER_MONITORSCREEN_DEFAULT;
            }

            if (string.IsNullOrWhiteSpace(iniTimerHeartbeat) ||
                !ushort.TryParse(iniTimerHeartbeat, out outTimerHeartbeat) ||
                outTimerHeartbeat < EnvUtilities.TIMER_HEARTBEAT_MIN ||
                outTimerHeartbeat > EnvUtilities.TIMER_HEARTBEAT_MAX)
            {
                isOK = false;
                outTimerHeartbeat = EnvUtilities.TIMER_HEARTBEAT_DEFAULT;
            }

            // 写入全局静态变量中保存
            EnvUtilities.TabCountMonitorScreen = outTabCountMonitorScreen;
            EnvUtilities.TimerMonitorScreen = outTimerMonitorScreen;
            EnvUtilities.TimerHeartbeat = outTimerHeartbeat;

            // 写对应值到 ini 文件
            if (!isOK)
            {
                iniOperation.WriteValue(EnvUtilities.INI_SECTIONNAME_MONITORSCREEN,
                    EnvUtilities.INI_KEYNAME_MONITORSCREEN_TABCOUNT, outTabCountMonitorScreen.ToString(), iniPath);
                iniOperation.WriteValue(EnvUtilities.INI_SECTIONNAME_MONITORSCREEN,
                    EnvUtilities.INI_KEYNAME_MONITORSCREEN_INTERVAL, outTimerMonitorScreen.ToString(), iniPath);
                iniOperation.WriteValue(EnvUtilities.INI_SECTIONNAME_HEARTBEAT,
                    EnvUtilities.INI_KEYNAME_HEARTBEAT_INTERVAL, outTimerHeartbeat.ToString(), iniPath);
            }
        }

        #region 导航栏
        /// <summary>
        /// 生成导航面板
        /// </summary>
        private void _generateNavigation()
        {
            if (this._moduleCatalog != null && this._moduleCatalog.Modules.Count() > 0)
            {
                //////////////////////////////////////////////////////////////////////////
                // 这里根据 App.config 动态添加导航栏
                //////////////////////////////////////////////////////////////////////////
                foreach (ModuleInfo module in this._moduleCatalog.Modules)
                {
                    switch (module.ModuleName)
                    {
                        case "TreeMgtModule":
                            _setAccordionItem("TreeMgt", "组织机构", module.ModuleName, ViewNames.TreeMgtModule_CategoryTree);
                            break;


                        default:
                            break;
                    }
                }
            }
        }

        /// <summary>
        /// 设置导航分组
        /// </summary>
        /// <param name="imageName">图片名称</param>
        /// <param name="textDesc">文字描述</param>
        /// <param name="moduleName">模块名称</param>
        /// <param name="mainView">主界面</param>
        private void _setAccordionItem(string imageName,
            string textDesc, string moduleName, string mainView)
        {
            if (string.IsNullOrWhiteSpace(imageName) || string.IsNullOrWhiteSpace(textDesc) ||
                string.IsNullOrWhiteSpace(moduleName) || string.IsNullOrWhiteSpace(mainView))
            {
                return;
            }

            // 定义图片
            Image headImage = new Image();
            headImage.Height = headImage.Width = 25;
            headImage.Margin = new Thickness(5, 0, 5, 0);
            headImage.Source = new BitmapImage(new Uri(
                string.Format(ConstantString.IMAGE_URL, imageName), UriKind.RelativeOrAbsolute));

            // 定义文字
            TextBlock headText = new TextBlock();
            headText.FontSize = 20;
            headText.Margin = new Thickness(20, 0, 0, 0);
            headText.FontFamily = new System.Windows.Media.FontFamily("Microsoft YaHei");
            headText.HorizontalAlignment = HorizontalAlignment.Center;
            headText.VerticalAlignment = VerticalAlignment.Center;
            headText.Text = textDesc;

            // 定义分组
            StackPanel headPanel = new StackPanel();
            headPanel.Orientation = Orientation.Horizontal;
            headPanel.HorizontalAlignment = HorizontalAlignment.Left;
            headPanel.VerticalAlignment = VerticalAlignment.Center;
            headPanel.Children.Add(headImage);
            headPanel.Children.Add(headText);

            // 定义“组”
            AccordionItem accItem = new AccordionItem();
            accItem.Header = headPanel;
            accItem.HorizontalAlignment = accItem.HorizontalContentAlignment = HorizontalAlignment.Stretch;
            accItem.VerticalAlignment = accItem.VerticalContentAlignment = VerticalAlignment.Stretch;
            ToolTipService.SetToolTip(accItem, textDesc);
            accItem.Background = Application.Current.Resources.MergedDictionaries[0][App.Current.Resources["FormBackgroundStyle"].ToString()] as Brush;
            accItem.Style = Application.Current.Resources.MergedDictionaries[0][App.Current.Resources["AccordionItemStyle"].ToString()] as Style;
            //accItem.Selected += (s, e) =>
            //{
            //    _changeIndicatorState(true);
            //    this._moduleManager.LoadModule(moduleName); // 按需加载模块
            //};
            this._eventAggregator.GetEvent<OpenModelEvent>().Publish(new OpenModelEventArg() { ModelName = moduleName }); // 事件通知
            App.Current.Dispatcher.BeginInvoke((Action)(() =>
            {
                accItem.Content = this._serviceLocator.GetInstance<Object>(mainView); // 解析并显示主界面
            }));

            this._navigationPanel.Items.Add(accItem); // 添加到导航栏
        }
        #endregion

        #region 子模块传入执行的方法
        /// <summary>
        /// 事件入口
        /// </summary>
        /// <param name="arg"></param>
        private void _manageData(OpenModelEventArg arg)
        {
            if (string.IsNullOrWhiteSpace(arg.FunctionName))
            {
#if DEBUG
                Debug.WriteLine("无效的执行操作，请输入方法名称！");
#endif
                return;
            }

            try
            {
                switch (arg.FunctionName)
                {

                    default:
                        break;
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
        }
        #endregion

        #endregion

        #region Public Events

        /// <summary>
        /// 关闭窗口时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (MessageBox.Show("是否退出系统？", ConstantString.MSG_COMPANY,
                MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.OK) == MessageBoxResult.OK)
            {
                this.Dispose();

                Application.Current.Shutdown(Environment.ExitCode);
                Environment.Exit(Environment.ExitCode);
            }
            else
            {
                e.Cancel = true;
            }
        }

        /// <summary>
        /// 导航面板加载时
        /// </summary>
        /// <param name="sender">Accordion Panel</param>
        /// <param name="e"></param>
        public void Navigation_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (sender != null && sender is Accordion)
                {
                    this._navigationPanel = sender as Accordion; // 得到导航面板
                    this._navigationPanel.Items.Clear(); // 防止重复加载

                    if (this._navigationPanel.Tag != null &&
                        this._navigationPanel.Tag is TabControl)
                    {
                        this._splitPanel = this._navigationPanel.Tag as TabControl; // 得到用户区
                        _generateNavigation(); // 生成导航栏
                    }
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
        }

        #endregion
    }
}
